import { List, Map } from 'immutable';
import { AtomicBlockUtils, EditorState, Entity, Modifier } from "draft-js";

export const insertBlock = (
  onChange: (e: EditorState) => void,
  editorState: EditorState,
  blockName: string,
  data: any
) => {

  const entityKey = Entity.create(blockName, "IMMUTABLE", data);
  const state = AtomicBlockUtils.insertAtomicBlock(
    editorState,
    entityKey,
    ' '
  );
  onChange(state);
}
/**
 * Function returns collection of currently selected blocks.
 */
export function getSelectedBlocksMap(editorState: EditorState) {
  const selectionState = editorState.getSelection();
  const contentState = editorState.getCurrentContent();
  const startKey = selectionState.getStartKey();
  const endKey = selectionState.getEndKey();
  const blockMap = contentState.getBlockMap();
  return blockMap
    .toSeq()
    .skipUntil((_, k) => k === startKey)
    .takeUntil((_, k) => k === endKey)
    .concat([[endKey, blockMap.get(endKey)]]);
}
/**
 * Function returns collection of currently selected blocks.
 */
export function getSelectedBlocksList(editorState: EditorState) {
  return getSelectedBlocksMap(editorState).toList();
}

/**
 * Function will return currently selected blocks meta data.
 */
export function getSelectedBlocksMetadata(editorState: EditorState) {
  // let metaData = new Map();
  let metaData = Map();
  const selectedBlocks = getSelectedBlocksList(editorState);
  if (selectedBlocks && selectedBlocks.size > 0) {
    for (let i = 0; i < selectedBlocks.size; i += 1) {
      const data = selectedBlocks.get(i).getData();
      if (!data || data.size === 0) {
        metaData = metaData.clear();
        break;
      }
      if (i === 0) {
        metaData = data;
      } else {
        metaData.forEach((value, key) => {
          // eslint-disable-line no-loop-func
          if (!data.get(key) || data.get(key) !== value) {
            metaData = metaData.delete(key);
          }
        });
        if (metaData.size === 0) {
          metaData = metaData.clear();
          break;
        }
      }
    }
  }
  return metaData;
}

/**
 * Function will add block level meta-data.
 */
export function setBlockData(editorState: EditorState, data: any) {
  const newContentState = Modifier.setBlockData(
    editorState.getCurrentContent(),
    editorState.getSelection(),
    data
  );
  return EditorState.push(editorState, newContentState, 'change-block-data');
}